let onlinePlayer = [{ "name": '123', "password": ['0', '1', '2', '3'] }];
let passwordInputBox = [];

// game start
const game = {
	gameState: null,
	playername: null,
	password: [],
	scores: 0,
	// 已解锁英雄
	unlockHero: [0, 1, 7, 8],
	// 当前英雄
	hero: null,
	// 选择时记住用户的选择
	selectedHero: 0,
	selectedFaction: null,
	selectedMove: null,
	// 当前选中的pet的mid 新获得的宠物的id
	selectedPet: null,
	// 当前地图
	cur_map: [],
	// 当前地图层数
	cur_map_floor: -1,
	// 当前英雄位置 0~35
	cur_hero_pos: null,
	// 当前移动的回合数
	cur_map_turn: 0,
	unlockHeroFunc: function () {
		// 使用分数解锁英雄 上传服务器
	},
	cleanAndEnterMenu: function () {
		this.scores += this.cur_map_turn * (this.cur_map_floor - 1) + (this.hero.itemId.length + this.hero.petInfo.petNum[0] + this.hero.petInfo.petNum[1] + this.hero.heroInfo.hasMove) * 2;
		renderScores();
		// 上传服务器
		// 归零
		this.hero = null;
		this.selectedFaction = null;
		this.selectedHero = 0;
		this.selectedMove = null;
		this.selectedPet = null;
		this.gameState = 'menu';
		this.cur_map = [];
		this.cur_map_floor = -1;
		this.cur_hero_pos = null;
		this.cur_map_turn = 0;
		document.querySelector('.gameScreen').style.display = "none";
		document.querySelector('.menuscreen').style.display = "block";
		document.querySelector('.gameScreen .map ul').innerText = '';
	},
	startPage: function () {
		// 开始页第一步 选择角色 势力 技能
		let ul = document.querySelector('.choice .bottom_row ul');
		let _f = document.createDocumentFragment();
		ul.innerHTML = '';
		let _arr = null;
		let pic = null;
		let dirname = '';
		switch (game.gameState) {
			case 'choiceHero':
				_arr = game.unlockHero;
				pic = heroesNames;
				dirname = 'character';
				break;
			case 'choiceFaction':
				_arr = game.hero.faction;
				game.selectedFaction = Number(_arr[0]);
				pic = factionsNames;
				dirname = 'factions';
				break;
			case 'choiceMove':
				_arr = game.hero.moveTree;
				game.selectedMove = _arr[0];
				pic = movesNames;
				dirname = 'move';
				break;
			default:
				break;
		}
		for (let i = 0; i < _arr.length; i++) {
			const li = document.createElement('li');
			let j = (li.dataset.id = _arr[i]);
			li.style.background = `url(icon/${dirname}/${pic[j]}.png)`;
			if (i == 0) {
				// 默认显示第一个
				addClass(li, 'select');
			}
			// 选择角色 li.addEventListener('click', game.renderSelectHero(i)); 能传递参数吗？
			li.addEventListener('click', renderSelect);
			_f.appendChild(li)
		}
		ul.appendChild(_f);
		renderSelectTips()
	},
	setPage: function () {
		console.log("设置页");
	},
	collectPage: function () {
		console.log("图鉴页");
	},
	startMapPage: function (floor) {
		// 开始页第二步 生成地图
		if (floor == 0) {
			document.querySelector('.choice').style.display = "none";
			document.querySelector('.gameScreen').style.display = "block";
			game.cur_map_floor++;
			game.genMap(game.cur_map_floor);
			renderMap();
			renderHeroStat();
			game.cur_hero_pos = -1;
			game.gameState = 'start';
		}
		console.log("渲染地图" + floor);
	},
	handleButton: function (e) {
		// 处理菜单界面的三种按钮
		if (game.gameState == 'menu') {
			document.querySelector('.menuscreen').style.display = "none"
		}
		switch (e.target.id) {
			case 'startBtn':
				game.gameState = 'choiceHero';
				game.startPage();
				// 允许点击下一步按钮
				document.querySelector('.choice').style.display = 'flex';
				document.querySelector('.choice .main_row button').addEventListener("click", game.handleSelectBtn);
				break;
			case 'collectBtn':
				game.collectPage();
				break;
			case 'setBtn':
				game.setPage();
				break;
			default:
				break;
		}
	},
	handleSelectBtn: (e) => {
		// 处理开始页第一步的三种选择
		switch (game.gameState) {
			case 'choiceHero':
				game.hero = new Hero(game.selectedHero);
				game.gameState = 'choiceFaction';
				game.startPage()
				break;
			case 'choiceFaction':
				game.gameState = 'choiceMove';
				game.startPage()
				break;
			case 'choiceMove':
				game.gameState = 'initMap';
				game.startMapPage(0);
				break;
			default:
				break;
		}
	},
	handleClickMap: (e) => {
		// 处理开始页第二步 点击地图块
		let i = e.target.dataset.i;
		game.enterNewArea(i);
	},
	enterNewArea: (i) => {
		game.cur_hero_pos = Number(i);
		game.cur_map_turn++;
		let _cur_map = document.querySelectorAll(".gameScreen .map ul li")
		if (typeof game.cur_hero_pos == "number") {
			let _cur = document.querySelector(".curpos");
			_cur && removeClass(_cur, "curpos");
			// removeClass(document.querySelectorAll(".gameScreen .map ul li")[game.cur_hero_pos], "curpos");
		}
		if (game.cur_map[i][0] == 1 && game.cur_map[i][1] == 3) {
			// [0]==1 地点 [1]==3 出口
			console.log("enter exit door");
			// 一层 二层+1 三层+1 BOSS层+1 一共4个技能
			game.cur_map_floor++;
			game.genMap(game.cur_map_floor)
			renderMap()
		} else {
			if (containsClass(_cur_map[i], 'gone')) {
				console.log("你已探索此地");
				// 已到过的地块
				game.cur_map_turn++;
			} else {
				addClass(_cur_map[i], 'gone');
				// 依据地块类别，交由不同的处理器处理
				if (game.cur_map[i][0] == 1) {
					gameInfoSpan[2].innerText = "你发现了" + areaTips[game.cur_map[i][1]][0] + ":" + areaTips[game.cur_map[i][1]][1];
					eventHandler(game.cur_map[i][1])
				} else {
					battleHandler(game.cur_map[i][1])
				}
			}
			addClass(_cur_map[i], 'curpos');
			// 点亮周围可选择的地块
			renderMapHints()
		}
	},
	genMap: (l) => {
		let total = [];
		let cur = null, res = [];
		if (l < 3) {
			for (let i = 0; i < monsterLevel[l].length; i++) {
				cur = [0, monsterLevel[l][i]]
				total.push(cur)
			}
			for (let i = 0; i < areaTips.length; i++) {
				if (i == 3) {
					continue;
				}
				cur = [1, i]
				total.push(cur)
			}
		}
		// 只从 monster 和 area 中选取
		switch (l) {
			case 0:
				for (let i = 0; i < 36; i++) {
					if (i == 14 || i == 15 || i == 20 || i == 21) {
						res.push([1, 3]);
					} else {
						res.push(total[getRandomRange(0, total.length - 1)]);
					}
				}
				break;
			case 1:
				for (let i = 0; i < 36; i++) {
					if (i == 0 || i == 5 || i == 30 || i == 35) {
						res.push([1, 3]);
					} else {
						res.push(total[getRandomRange(0, total.length - 1)]);
					}
				}
				break;
			case 2:
				for (let i = 0; i < 36; i++) {
					if (i == 14 || i == 15 || i == 20 || i == 21) {
						res.push([1, 3]);
					} else {
						res.push(total[getRandomRange(0, total.length - 1)]);
					}
				}
				break;
			case 3:
				// 一港口 一营地 一boss
				res.push([1, 0], [1, 16]);
				res.push([0, getRandomRange(0, 6)]);
				break;
			case 4:
				// 生成用于副本的小地图
				// 渲染2个非门类的事件块2个小怪块1个小boss块1个出口地块
				res.push([0, 2], [1, 0], [0, 3], [1, 16], [0, 0], [1, 3]);
				break;
			default:
				break;
		}
		if (l < 4) {
			// 测试港口
			// res[0] = [1, 1];
			game.cur_map = res;
		} else {
			return res;
		}
		// console.log(game.cur_map);
	}
}

if (!game.playername) {
	document.querySelector('.loginbox button').addEventListener("click", handleLoginBtn)
}

function handleLoginBtn(e) {
	let name = document.querySelector('.loginbox input').value;
	if (!name) {
		window.alert('名称不能为空')
		return;
	}
	if (onlinePlayer.map(e => e.name).indexOf(name) != -1) {
		console.log(name + "进入游戏");
		game.gameState = 'login';
	} else {
		console.log(name + "注册游戏");
		game.gameState = 'register';
	}
	game.playername = name;
	document.querySelector('.loginbox').style.display = "none";
	let lis = document.createDocumentFragment();
	// 加载 16 个 图标
	for (let i = 0; i < 43; i++) {
		const li = document.createElement('li');
		li.dataset.id = i;
		li.addEventListener('click', game.gameState == 'login' ? enterMenu : setpassword);
		li.style.backgroundImage = `url(icon/monster/${monsterNames[i]}.png)`;
		lis.appendChild(li);
	}
	document.querySelector('.passwordbox ul').appendChild(lis);
	document.querySelector('.passwordbox').style.display = "block";
}
function setpassword(e) {
	if (game.password.length < 4) {
		const i = e.target.dataset.id;
		if (game.password.indexOf(i) == -1) {
			addClass(e.target, 'select')
			game.password.push(i)
		}
	}
	if (game.password.length == 4) {
		initMenu()
	}
}
function enterMenu(e) {
	if (passwordInputBox.length < 4) {
		const i = e.target.dataset.id;
		if (passwordInputBox.indexOf(i) == -1) {
			addClass(e.target, 'select')
			passwordInputBox.push(i)
		}
	}
	if (passwordInputBox.length == 4) {
		let _flag = true;
		let rightPassword = onlinePlayer.filter(e => e.name == game.playername)[0].password;
		for (let i = 0; i < passwordInputBox.length; i++) {
			if (rightPassword[i] != passwordInputBox[i]) {
				_flag = false;
				break;
			}
		}
		if (_flag) {
			initMenu()
		} else {
			let ul = document.querySelector('.passwordbox ul');
			for (let i = 0; i < passwordInputBox.length; i++) {
				removeClass(ul.children[passwordInputBox[i]], 'select');
			}
			passwordInputBox = [];
			window.alert('密码错误');
		}
	}
}
function initMenu() {
	// 移除登录按钮的监听
	document.querySelector('.loginbox button').removeEventListener('click', handleLoginBtn);
	// 进入菜单页
	document.querySelector('.passwordbox').style.display = "none";
	document.querySelector('.menuscreen .top_row .playername').innerText = game.playername;
	document.querySelector('.menuscreen .top_row .scores').innerText = game.scores;
	document.querySelector('.menuscreen').style.display = "block";
	let buttons = document.querySelectorAll('.menuscreen .middle_col button')
	for (let i = 0; i < buttons.length; i++) {
		const button = buttons[i];
		button.dataset.id = i;
		button.addEventListener('click', game.handleButton)
	}
	game.gameState = 'menu';
}